import React, { useEffect, useState, useCallback, memo } from 'react'
import style from './guess.module.scss'
import { recommend } from '@/service/api'
import { formatUrl } from '@/utils/index'
import LoadImg from '../loadImg/LoadImg'

const Guess = props => {
  const [list, setList] = useState([])

  // 使用useCallback缓存函数，当props.id发生改变，重新创建函数
  const randomBook = useCallback(() => {
    // 获取同类书籍
    recommend(props.id || '5ebde2fa31edb31000320660').then(res => {
      let arr = [] 
      // 随机截取4本书
      while(arr.length < 4) {
        let index = Math.floor(Math.random() * res.books.length)
        if (!arr.find(item => item._id === res.books[index]._id)) {
          arr.push(res.books[index])
        }
      }
      setList(arr.slice(0, 4).map(book => ({...book, cover: formatUrl(book.cover)})))
    })
  }, [props.id])

  useEffect(() => {
    randomBook()
  }, [])

  return (
    <div className={style.wrap}>
      <h2>{props.title}</h2>
      <div className={style.list}>
        {list.map(item =>
          <dl key={item._id}>
            <dt>
              <LoadImg className={style.img} url={item.cover} />
            </dt>
            <dd>
              <p>{item.title}</p>
              <span>{item.author}</span>
            </dd>
          </dl>
        )}
      </div>
      <div className={style.change}><span onClick={randomBook}>换一批</span></div>
    </div>
  )
}

// memo: 性能优化，组件内的状态发生改变才重新渲染组件
export default memo(Guess)
